//
//  WBTabBar.swift
//  SinaWeibo_Swift
//
//  Created by TianZhen on 16/4/8.
//  Copyright © 2016年 TianZhen. All rights reserved.
//

import UIKit

class WBTabBar: UITabBar {

    // 定义 block
    var plusButtonClick: (() -> ())?

    /// MARK - 布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()

        let count = 5
        let width = bounds.width / CGFloat(count)
        
        var index = 0
        // 遍历子控件 布局
        for subItem in subviews
        {
            // 判断是不是 tarbarButton
            if subItem.isKindOfClass(NSClassFromString("UITabBarButton")!)
            {
                // 赋值 frame
                subItem.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: bounds.height)
                index++
                
                // 如果是index = 2 空出一个位置给加号按钮
                if index == 2
                {
                    index++
                }
            }
        }
        plusButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: bounds.height)
    }
    
    // 加号按钮点击事件
    func btnClick()
    {
        // 调用 block
        plusButtonClick!()
    }
    
    /// MARK - 懒加载
    lazy var plusButton: UIButton = {
    
        let button = UIButton()
        
        // 设置背景图
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        // 设置前景图
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        self.addSubview(button)
        
        // 添加点击事件
        button.addTarget(self, action: "btnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
}
